<template>
  <el-popover :trigger="trigger" v-model:visible="visible" width="310px" placement="bottom-start">
    <template #default>
      <el-input v-model="searchValue" placeholder="输入英文关键词进行搜索" @input="filterIcon" :suffix-icon="Search" />
      <div class="icon-box">
        <div
          v-for="(item,index) in iconArr"
          :key="index"
          @click="handleClick(item)"
          class="icon-content"
          :style="{ background: icon === item ? 'var(--el-color-primary)' : ''}"
        >
          <el-tooltip placement="top">
            <template #content>
              <span>{{ item }}</span>
            </template>
            <svg-icon :icon-class="item"/>
          </el-tooltip>
        </div>
      </div>
    </template>
    <template #reference>
      <slot></slot>
    </template>
  </el-popover>
</template>

<script>
import icons from '@/assets/icons/index'
import { Search } from '@element-plus/icons-vue'
import SvgIcon from "@/components/SvgIcon/index.vue";
export default defineComponent({
  name: 'IconPicker',
  components: {SvgIcon},
  computed: {
    Search() {
      return Search
    }
  },
  props: {
    icon:{
      type:String,
      required:false
    },
    //自定义触发方式
    trigger:{
      type:String,
      default: 'click',
      validator: function(value) {
        return ['click', 'hover', 'focus'].indexOf(value) !== -1
      }
    }
  },
  setup(props, context) {
    const iconArr = ref(icons)
    const visible = ref(false)
    const searchValue = ref('')

    const handleClick = (icon)=>{
      context.emit('updateIcon',icon)
      visible.value = false;
    }

    /**
     * 进行搜索过滤
     */
    const filterIcon = ()=>{
      if (searchValue.value){
        iconArr.value = icons.filter((item) =>  item.toLowerCase().includes(searchValue.value.toLowerCase()) )
      }else{
        iconArr.value = icons;
      }
    }

    watch(visible,()=>{
      searchValue.value = ''
      iconArr.value = icons;
    })

    return {
      visible,
      iconArr,
      handleClick,
      searchValue,
      filterIcon
    }
  }
})
</script>

<style scoped lang="scss">
.icon-box{
  overflow: auto;
  font-size: 20px;
  width: 280px;
  height: 230px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-content: flex-start;
  justify-content: center;
}

.icon-content{
  width: 45px;
  height: 40px;
  margin:  10px;
  cursor: pointer;
  text-align: center;
  border-radius: 6px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;

}

.icon-content:hover{
  background: #e7e6e6;
}
</style>
